package com.yunsc.store.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yunsc.common.exception.YunscException;
import com.yunsc.common.utils.PageResult;
import com.yunsc.store.dao.YunscUserGradeDao;
import com.yunsc.store.dto.UserGradeDTO;
import com.yunsc.store.entity.YunscUserGradeEntity;
import com.yunsc.store.service.YunscUserGradeService;
import com.yunsc.store.vo.UserGradeVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("yunscUserGradeService")
public class YunscUserGradeServiceImpl extends ServiceImpl<YunscUserGradeDao, YunscUserGradeEntity> implements YunscUserGradeService {

    // 创建单例的ObjectMapper
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public List<UserGradeVO> queryUserGradeAll(Integer storeId) {
        LambdaQueryWrapper<YunscUserGradeEntity> lqw = new LambdaQueryWrapper<YunscUserGradeEntity>()
                .eq(YunscUserGradeEntity::getStatus, 1)
                .eq(YunscUserGradeEntity::getStoreId, storeId)
                .eq(YunscUserGradeEntity::getIsDelete, 0);
        List<YunscUserGradeEntity> userGradeEntities = this.list(lqw);
        if (CollectionUtils.isEmpty(userGradeEntities)) {
            return null;
        }
        return userGradeEntities.stream().map(YunscUserGradeServiceImpl::convertToUserGradeVO).collect(Collectors.toList());

    }

    @Override
    public PageResult<UserGradeVO> queryUserGradeList(Integer currentPage, Integer storeId) {
        LambdaQueryWrapper<YunscUserGradeEntity> lqw = new LambdaQueryWrapper<YunscUserGradeEntity>()
                .eq(YunscUserGradeEntity::getStoreId, storeId)
                .eq(YunscUserGradeEntity::getIsDelete, 0)
                .orderByAsc(YunscUserGradeEntity::getSort);
        List<YunscUserGradeEntity> gradeEntityList = this.list(lqw);
        List<UserGradeVO> collect = gradeEntityList.stream().map(YunscUserGradeServiceImpl::convertToUserGradeVO).collect(Collectors.toList());
        return PageResult.formatPageResult(collect, currentPage, collect.size(), collect.size());
    }

    @Override
    @Transactional
    public void editUserGrade(UserGradeDTO userGradeParam) {
        Integer gradeId = userGradeParam.getGradeId();
        YunscUserGradeEntity userGradeEntity = this.getById(gradeId);
        if (userGradeEntity == null) {
            return;
        }
        UserGradeVO userGradeForm = userGradeParam.getForm();
        BeanUtils.copyProperties(userGradeForm, userGradeEntity);
        userGradeEntity.setEquity(JSON.toJSONString(userGradeForm.getEquity()));
        userGradeEntity.setUpgrade(JSON.toJSONString(userGradeForm.getUpgrade()));
        userGradeEntity.setGradeId(gradeId);
        boolean update = this.updateById(userGradeEntity);
        if (!update) {
            throw new YunscException("更新会员等级失败");
        }
    }

    @Override
    @Transactional
    public void removeUserGrade(Integer gradeId) {
        boolean update = this.update(new UpdateWrapper<YunscUserGradeEntity>()
                .eq("grade_id", gradeId).set("is_delete", 1));
        if (!update) {
            throw new YunscException("删除会员等级失败");
        }
    }

    @Override
    @Transactional
    public void addUserGrade(UserGradeDTO userGradeParam, Integer storeId) {
        YunscUserGradeEntity userGradeEntity = new YunscUserGradeEntity();
        UserGradeVO userGradeForm = userGradeParam.getForm();
        BeanUtils.copyProperties(userGradeForm, userGradeEntity);
        userGradeEntity.setEquity(JSON.toJSONString(userGradeForm.getEquity()));
        userGradeEntity.setUpgrade(JSON.toJSONString(userGradeForm.getUpgrade()));
        userGradeEntity.setStoreId(storeId);
        boolean save = this.save(userGradeEntity);
    }

    @Override
    public YunscUserGradeEntity queryUserGrade(Integer userId) {
        return this.baseMapper.selectUserGrade(userId);
    }


    // 转换为用户等级VO
    public static UserGradeVO convertToUserGradeVO(YunscUserGradeEntity userGrade) {
        UserGradeVO userGradeVO = new UserGradeVO();
        BeanUtils.copyProperties(userGrade, userGradeVO);
        try {
            userGradeVO.setEquity(objectMapper.readValue(userGrade.getEquity(), Map.class));
            userGradeVO.setUpgrade(objectMapper.readValue(userGrade.getUpgrade(), Map.class));
        } catch (JsonProcessingException e) {
            throw new YunscException("解析JSON时出错", e);
        }

        return userGradeVO;
    }


    // private static UserGradeVO convertToUserGradeVO(YunscUserGradeEntity userGrade) {
    //     UserGradeVO userGradeDto = new UserGradeVO();
    //     BeanUtils.copyProperties(userGrade, userGradeDto);
    //     // 将JSON字符串转换为Map对象
    //     String equityStr = userGrade.getEquity();
    //     Map<String, Object> mapEquity = JSON.parseObject(equityStr, Map.class);
    //     userGradeDto.setEquity(mapEquity);
    //     String upgradeStr = userGrade.getUpgrade();
    //     Map<String, Object> mapUpgrade = JSON.parseObject(upgradeStr, Map.class);
    //     userGradeDto.setUpgrade(mapUpgrade);
    //     return userGradeDto;
    // }

}